package com.spark.gaea.data.mybatis.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.spark.gaea.data.config.DataSourceConfig;
import com.spark.gaea.data.mybatis.DataPermissionsBacked;
import com.spark.gaea.data.mybatis.interceptor.SqlStatementInterceptor;
import com.spark.gaea.utils.componet.ComponentContext;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.io.Resource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@Import({DataSourceConfig.class})
public abstract class AbstractMyBatisSQLConfig {
	@Autowired
	private ComponentContext context;
	@Autowired
	private DruidDataSource dataSource;

	public abstract DataPermissionsBacked dataPermissionsBacked();

	@Bean
	public Interceptor sqlStatementInterceptor() {
		return new SqlStatementInterceptor();
	}

	@Bean
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		final SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
		factoryBean.setDataSource(this.dataSource);
		final Resource[] resources = this.context.getApplicationContext().getResources("classpath*:mappers/**/*.xml");
		factoryBean.setMapperLocations(resources);
		final Interceptor[] interceptors = {this.sqlStatementInterceptor()};
		factoryBean.setPlugins(interceptors);
		return factoryBean.getObject();
	}
}
